<template>
  <el-dialog
    :title="title"
    :visible="visible"
    width="800px"
    append-to-body
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="核查指标">
        <el-input :value="targetName" disabled />
      </el-form-item>
      <el-form-item label="核查要点" prop="keyName">
        <el-select v-model="form.keyName" :disabled="operationType === 'edit'" style="width: 240px">
          <el-option
            v-for="dict in keyOpts"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="核查要素" prop="element">
        <el-input v-model="form.element" placeholder="请输入核查要素" />
      </el-form-item>
      <el-form-item label="核查基准数据" prop="basicInfo">
        <el-input v-model="form.basicInfo" placeholder="请输入核查基准数据" />
      </el-form-item>
      <el-form-item label="核查内容">
        <el-input v-model="form.content" />
      </el-form-item>
      <template v-if="operationType === 'add'">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="序号" prop="itemSort">
          <el-input v-model="form.itemSort" placeholder="请输入排序字段" />
        </el-form-item>
        <el-form-item label="问题等级" prop="itemLevel">
          <el-select v-model="form.itemLevel" placeholder="请选择问题等级">
            <el-option
              v-for="dict in dict.type.sys_dict_problem_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择显示类型">
            <el-option
              v-for="dict in dict.type.view_component_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示内容描述" prop="typeDesc">
          <el-input v-model="form.typeDesc" placeholder="请输入显示内容描述" />
        </el-form-item>
        <el-form-item label="是否需要上传照片" prop="needImage">
          <el-select v-model="form.needImage" placeholder="请选择显示类型">
            <el-option
              v-for="dict in dict.type.sys_dict_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="核查结果" prop="result">
          <el-radio-group v-if="form.type === 'radio'" v-model="form.result" @input="validateField('result')">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
            <el-radio label="2">不涉及</el-radio>
          </el-radio-group>
          <el-input
            v-else
            v-model="form.result"
            type="textarea"
            placeholder="请输入核查结果"
          />
        </el-form-item>
        <el-form-item label="原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入原因" />
        </el-form-item>
        <el-form-item label="整改措施" prop="modifiedMethod">
          <el-input v-model="form.modifiedMethod" type="textarea" placeholder="请输入整改措施" />
        </el-form-item>
        <el-form-item v-if="form.needImage" label="附件">
          <el-upload
            action="#"
            multiple
            :file-list="form.fileList"
            :auto-upload="false"
            :on-preview="previewImage"
            :before-remove="beforeRemoveImage"
            :on-remove="handleRemoveImage"
            :on-change="handleImage"
          >
            <i slot="default" class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-loading="loading" type="primary" @click="submit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { deleteFile } from '@/api/system/file'

export default {
  name: 'SecurityDialog',
  dicts: ['sys_dict_problem_level', 'view_component_type', 'sys_dict_yes_no'],
  props: {
    taskId: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    initData: {
      type: Object,
      default: () => undefined
    },
    targetName: {
      type: String,
      required: true
    },
    targetOpts: {
      type: Array,
      default: () => []
    },
    keyOpts: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      fileList: [],
      form: {},
      operationType: 'add',
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        content: [
          { required: true, message: '核查内容不能为空', trigger: 'blur' }
        ],
        result: [
          { required: true, message: '核查结果不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    visible: function(val) {
      if (val) {
        this.form = this.getInitFormData()
        this.fileList = this.initData.fileList.slice()
      }
    }
  },
  methods: {
    getInitFormData() {
      let output = {
        targetName: this.targetName,
        fileList: []
      }
      this.operationType = 'add'
      if (this.initData) {
        this.operationType = 'edit'
        output = {
          ...this.initData
        }
      }
      return output
    },
    validateField(field) {
      this.$refs.form.validateField(field)
    },
    getFileBlobUrl(file) {
      if (window.createObjectURL) {
        return window.createObjectURL(file)
      } else if (window.URL) {
        return window.URL.createObjectURL(file)
      } else if (window.webkitURL) {
        return window.webkitURL.createObjectURL(file)
      }
    },
    handleImage(file, fileList) {
      this.form.fileList = fileList
    },
    beforeRemoveImage(file) {
      return new Promise((resolve, reject) => {
        this.$modal.confirm(`确认删除？`).then(function() {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    async handleRemoveImage(file) {
      if (file.id) {
        await deleteFile(file.id)
      }
      let deleteIdx
      for (let i = 0, len = this.form.fileList.length; i < len; i++) {
        if (this.form.fileList[i].id === file.id || this.form.fileList[i].uid === file.uid) {
          deleteIdx = i
          break
        }
      }
      this.form.fileList.splice(deleteIdx, 1)
    },
    previewImage(file) {
      if (file.raw.type.includes('image')) {
        const url = this.getFileBlobUrl(file.raw)
        this.dialogImageUrl = url
        this.dialogVisible = true
      }
    },
    cancel() {
      this.loading = false
      this.form = {}
      this.resetForm('form')
      this.$emit('cancel')
    },
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          const formData = {
            id: '',
            targetId: this.targetOpts.find(item => item.label === this.targetName)?.value,
            taskId: this.taskId,
            ...this.form
          }
          this.$emit('submit', formData)
        }
      })
    }
  }
}
</script>
